package cn.lg.soar.system.monitor.controller;

import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.monitor.entity.RefreshToken;
import cn.lg.soar.system.monitor.service.impl.RefreshTokenServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Set;

/**
 * @author luguoxiang
 * @date 2021/10/16
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Api(tags = {"在线用户管理"})
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/token")
public class TokenInfoController {

    @Autowired
    private RefreshTokenServiceImpl refreshTokenService;

    @ApiOperation("在线用户")
    @GetMapping(value = "query", name = "在线用户")
    public HttpResult<PageResult<RefreshToken>> query(PageQuery pageQuery, RefreshToken tokenInfo) {
        LambdaQueryWrapper<RefreshToken> wrapper = Wrappers.<RefreshToken>lambdaQuery()
                .ge(RefreshToken::getTokenExpires, LocalDateTime.now())
                .eq(Objects.nonNull(tokenInfo.getUserId()), RefreshToken::getUserId, tokenInfo.getUserId())
                .eq(Objects.nonNull(tokenInfo.getDeviceType()), RefreshToken::getDeviceType, tokenInfo.getDeviceType())
                .eq(Objects.nonNull(tokenInfo.getIp()), RefreshToken::getIp, tokenInfo.getIp());
        Page<RefreshToken> page = this.refreshTokenService.page(
                new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize()),
                wrapper
        );
        PageResult<RefreshToken> result = new PageResult<>();
        result.setPageNo(pageQuery.getPageNo());
        result.setPageSize(pageQuery.getPageSize());
        result.setTotal(page.getTotal());
        result.setList(page.getRecords());
        return HttpResult.data(result);
    }

    @ApiOperation("强制下线")
    @PostMapping(value = "offline", name = "强制下线")
    public HttpResult<Void> offline(@RequestBody Set<String> ids) {
        this.refreshTokenService.removeByIds(ids);
        return HttpResult.success();
    }

}
